-
Notifications
You must be signed in to change notification settings - Fork 563
Property delegates for Activity extras #440
base: master
Are you sure you want to change the base?
Conversation
Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). 📝 Please visit https://cla.developers.google.com/ to sign. Once you've signed (or fixed any issues), please reply here (e.g. What to do if you already signed the CLAIndividual signers
Corporate signers
|
I signed it! |
CLAs look good, thanks! |
You're missing the default value parameter |
@dovahkiin98 What do you mean? Where? |
@gabrielhuff when you use intent.getStringExtra("extra", "") you provide a default value, it's not always 0 or "" or false, sometimes it's different. inline fun <T> Activity.extra(key: String, defaultValue: T) = lazy {
when(T::class.java) {
Int::class.java -> intent.getIntExtra(key, defaultValue) as T
Float::class.java -> intent.getFloatExtra(key, defaultValue) as T
...
}
}
val intExtra: Int by extra("intExtra", 2) |
@dovahkiin98 The current implementation allows you to define default values. The only difference is that we are getting them from a function instead of a raw value: val intExtra by extra("intExtra") { 2 } Note that you can omit the default value function. If so, the implementation will throw an |
- Add example with default value - Document default function
Delegates are an expensive hammer to use for this. I don't think we've decided whether their use is appropriate for simple things like this. |
IMHO delegates (in this case, specifically lazy instantiation) are perfect for this. Consider a scenario in which you need to access the same extra on different scopes. What would be the most appropriate way to do it? |
A I have no idea what "same extra on different scopes" means. |
By different scopes I mean different methods / contexts. We don't want to read the same extra from the input intent more than once (not because of performance - just because the call might be kinda ugly): override fun onCreate(state: Bundle?) {
...
val extra = intent.getParcelableExtra("my_key") as MyCustomExtra
}
fun onSomethingElse() {
val extra = intent.getParcelableExtra("my_key") as MyCustomExtra // Eww
} But I get what you're saying. Performance-wise, |
This implements #265. Usage: